package com.at.service.impl;

import com.at.dao.CommentDao;
import com.at.domain.Comment;
import com.at.service.CommentServce;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author : code1997
 * @date :2020-10-2020/10/16 20:29
 */
@Service
public class CommentServceImpl implements CommentServce {
    @Autowired
    private CommentDao commentDao;


    /**
     * 将获取到的评论进行处理，分级显示
     * @param blogId：
     * @return ：评论集
     */
    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        List<Comment> comments = commentDao.findByBlogIdAndParentCommentIsNull(
                blogId, Sort.by(Sort.Direction.DESC, "createTime"));
        return eachComment(comments);
    }

    @Transactional
    @Override
    public Comment saveComment(Comment comment) {
        Long parentCommentId=comment.getParentComment().getId();
        if (parentCommentId!=-1){
            //说明是回复某个评论
            comment.setParentComment(commentDao.getOne(parentCommentId));
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentDao.save(comment);
    }

    /**
     * 循环每一个顶层节点
     * @param comments:顶级节点
     * @return ：顶级节点的及其子集合
     */
    private List<Comment> eachComment(List<Comment> comments){
        //创建一个集合对集合进行存储，防止修改对象的属性造成整个集合的修改
        List<Comment> commentsView = new ArrayList<>();
        for (Comment comment : comments) {
            Comment c = new Comment();
            BeanUtils.copyProperties(comment, c);
            commentsView.add(c);
        }
        /*合并各层自带到第一级的子代集合中*/
        combineChildren(commentsView);
        return commentsView;
    }

    /**
     * @param comments :root根节点，blog不为空的对象集合
     */
    private void combineChildren(List<Comment> comments){
        for (Comment comment : comments) {
            List<Comment> replyComments = comment.getReplyComments();
            for (Comment replyComment : replyComments) {
                recursively(replyComment);
            }
            //将类的公共结构存放到自己的引用中去
            comment.setReplyComments(tempReplys);
            tempReplys=new ArrayList<>();
        }
    }

    /**
     * 存放子集的容器
     */
    private List<Comment> tempReplys=new ArrayList<>();

    private void recursively(Comment comment){
        tempReplys.add(comment);
        if (comment.getReplyComments().size()>0){
            List<Comment> replyComments = comment.getReplyComments();
            for (Comment replyComment : replyComments) {
                tempReplys.add(replyComment);
                if (replyComment.getReplyComments().size()>0){
                    recursively(replyComment);
                }
            }
        }
    }



}
